const db = require('../db');
function generateUniqueCode () {
  // 获取当前时间的时间戳
  const timestamp = Date.now().toString();
  // 定义一个字符串，包含所有可能的字符
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let randomChars = '';
  // 生成六位随机数（数字+字母组合）
  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    randomChars += chars[randomIndex];
  }
  // 组合成 code
  const code = `${timestamp}${randomChars}`;
  return code;
}
// 创建分享
const createShare = async (req, res, next) => {
  try {
    const { userId, shareName, fileList, folderList } = req.body;
    // 生成code时间戳+六位随机数或字母
    const code = generateUniqueCode();
    await db.query('INSERT INTO shares (userId, name,fileList, folderList,code) VALUES (?, ?, ?, ?,?)', [userId, shareName, JSON.stringify(fileList), JSON.stringify(folderList), code]);
    res.success({ data: code });
  }
  catch (error) {
    next(error);
  }
}
// 删除分享
const deleteShare = async (req, res, next) => {
  try {
    const { shareId } = req.params;
    await db.query('DELETE FROM shares WHERE id = ?', [shareId]);
    res.success({ data: "删除分享成功" });
  }
  catch (error) {
    next(error);
  }
}
// 获取用户的分享的文件
const getShared = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const [result] = await db.query('SELECT * FROM shares WHERE userId = ?', [userId]);
    if (result.length === 0) {
      return next();
    }

    res.success({ data: result });
  }
  catch (error) {
    next(error);
  }
}
// 获取分享详情
const getSharedDetails = async (req, res, next) => {
  try {
    const { shareCode } = req.params;
    const result = await db.query('SELECT * FROM shares WHERE shareCode = ?', [shareCode]);
    if (result.length === 0) {
      return res.status(404).json({ message: '分享不存在' });
    }
    const share = result[0];
    const files = await db.query('SELECT * FROM files WHERE fileList = ?', [share.fileList]);
    const folders = await db.query('SELECT * FROM folders WHERE folderList = ?', [share.folderList]);
    res.success({ data: [...folders, ...files] });
  }
  catch (error) {
    next(error);
  }
}
// 查看分享记录
const getShareRecords = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const result = await db.query('SELECT * FROM shares_visits WHERE userId = ?', [userId]);
    res.success({ data: result });
  }
  catch (error) {
    next(error);
  }
}
// 删除分享记录
const deleteShareRecord = async (req, res, next) => {
  try {
    const { shareId } = req.params;
    const result = await db.query('DELETE FROM shares_visits WHERE id = ?', [shareId]);
    res.success({ data: "删除分享记录成功" });
  }
  catch (error) {
    next(error);
  }
}

module.exports = {
  createShare,
  deleteShare,
  getShared,
  getSharedDetails,
  getShareRecords,
  deleteShareRecord,
};